import React from "react";
import {
  Card,
  Row,
  Col,
  Typography,
  Progress,
  Space,
  Tag,
  Divider,
  Table,
  Avatar,
} from "antd";
import {
  UserOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
} from "@ant-design/icons";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  RadarChart,
  Radar,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
} from "recharts";
import type { StudentPerformance } from "../types";
import styled from "styled-components";

const { Title, Text } = Typography;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

interface StudentAnalysisProps {
  performance: StudentPerformance;
  studentName: string;
}

const StudentAnalysis: React.FC<StudentAnalysisProps> = ({
  performance,
  studentName,
}) => {
  // 计算考试成绩趋势数据
  const examTrendData = performance.examResults.map((result) => ({
    name: result.examName,
    得分: result.score,
    平均分: 75, // TODO: 从实际数据中获取
  }));

  // 计算知识点掌握情况数据
  const knowledgeData = Object.entries(performance.knowledgePoints).map(
    ([name, data]) => ({
      subject: name,
      掌握度: data.mastery,
      趋势: data.trend[data.trend.length - 1] || 0,
    })
  );

  // 计算出勤率
  const attendanceRate =
    (performance.attendance.present / performance.attendance.total) * 100;

  // 计算作业完成率
  const homeworkRate =
    (performance.homeworkCompletion.completed /
      performance.homeworkCompletion.total) *
    100;

  return (
    <div>
      <StyledCard>
        <Row gutter={16} align="middle">
          <Col>
            <Avatar size={64} icon={<UserOutlined />} />
          </Col>
          <Col>
            <Title level={4}>{studentName}</Title>
            <Text type="secondary">学号：{performance.studentId}</Text>
          </Col>
        </Row>
      </StyledCard>

      <Row gutter={16}>
        <Col span={12}>
          <StyledCard title="考试成绩趋势">
            <LineChart
              width={500}
              height={300}
              data={examTrendData}
              margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Line
                type="monotone"
                dataKey="得分"
                stroke="#1890ff"
                activeDot={{ r: 8 }}
              />
              <Line type="monotone" dataKey="平均分" stroke="#52c41a" />
            </LineChart>
          </StyledCard>
        </Col>
        <Col span={12}>
          <StyledCard title="知识点掌握情况">
            <RadarChart width={500} height={300} data={knowledgeData}>
              <PolarGrid />
              <PolarAngleAxis dataKey="subject" />
              <PolarRadiusAxis angle={30} domain={[0, 100]} />
              <Radar
                name="掌握度"
                dataKey="掌握度"
                stroke="#1890ff"
                fill="#1890ff"
                fillOpacity={0.6}
              />
              <Legend />
            </RadarChart>
          </StyledCard>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <StyledCard title="出勤情况">
            <Space direction="vertical" style={{ width: "100%" }}>
              <Progress
                percent={attendanceRate}
                status={attendanceRate >= 90 ? "success" : "normal"}
              />
              <Row justify="space-between">
                <Col>
                  <Space>
                    <CheckCircleOutlined style={{ color: "#52c41a" }} />
                    <Text>出勤：{performance.attendance.present}次</Text>
                  </Space>
                </Col>
                <Col>
                  <Space>
                    <ClockCircleOutlined style={{ color: "#faad14" }} />
                    <Text>迟到：{performance.attendance.late}次</Text>
                  </Space>
                </Col>
                <Col>
                  <Space>
                    <WarningOutlined style={{ color: "#ff4d4f" }} />
                    <Text>缺勤：{performance.attendance.absent}次</Text>
                  </Space>
                </Col>
              </Row>
            </Space>
          </StyledCard>
        </Col>
        <Col span={12}>
          <StyledCard title="作业完成情况">
            <Space direction="vertical" style={{ width: "100%" }}>
              <Progress
                percent={homeworkRate}
                status={homeworkRate >= 90 ? "success" : "normal"}
              />
              <Row justify="space-between">
                <Col>
                  <Space>
                    <CheckCircleOutlined style={{ color: "#52c41a" }} />
                    <Text>
                      按时完成：{performance.homeworkCompletion.onTime}次
                    </Text>
                  </Space>
                </Col>
                <Col>
                  <Space>
                    <ClockCircleOutlined style={{ color: "#faad14" }} />
                    <Text>迟交：{performance.homeworkCompletion.late}次</Text>
                  </Space>
                </Col>
              </Row>
              <Divider>作业质量</Divider>
              <Progress
                percent={performance.homeworkCompletion.quality}
                steps={5}
                strokeColor={["#52c41a", "#52c41a", "#faad14", "#ff4d4f"]}
              />
            </Space>
          </StyledCard>
        </Col>
      </Row>

      <StyledCard title="需要加强的知识点">
        <Table
          dataSource={Object.entries(performance.knowledgePoints)
            .filter(([_, data]) => data.mastery < 60)
            .map(([name, data]) => ({
              name,
              mastery: data.mastery,
              trend: data.trend,
              weakPoints: data.weakPoints,
            }))}
          columns={[
            {
              title: "知识点",
              dataIndex: "name",
              key: "name",
            },
            {
              title: "掌握度",
              dataIndex: "mastery",
              key: "mastery",
              render: (mastery: number) => (
                <Progress
                  percent={mastery}
                  size="small"
                  status={mastery < 60 ? "exception" : "normal"}
                />
              ),
            },
            {
              title: "趋势",
              dataIndex: "trend",
              key: "trend",
              render: (trend: number[]) => {
                const latest = trend[trend.length - 1];
                const previous = trend[trend.length - 2];
                const diff = latest - (previous || 0);
                return (
                  <Tag color={diff >= 0 ? "success" : "error"}>
                    {diff >= 0 ? "+" : ""}
                    {diff.toFixed(1)}%
                  </Tag>
                );
              },
            },
            {
              title: "具体问题",
              dataIndex: "weakPoints",
              key: "weakPoints",
              render: (points: string[]) => (
                <Space size={[0, 4]} wrap>
                  {points.map((point) => (
                    <Tag key={point} color="warning">
                      {point}
                    </Tag>
                  ))}
                </Space>
              ),
            },
          ]}
          pagination={false}
        />
      </StyledCard>
    </div>
  );
};

export default StudentAnalysis;
